import { RichEditorProps } from "../toolbar"
import { ToggleButton } from "../components/ToggleButton"
import { ImageIcon } from '@radix-ui/react-icons';
import useOpenFile from "../hooks/useOpenFile";
import { file2canvas } from "../libs/imgToolbar";
import { insertBlock } from "../libs/draftjs-utils";
import withAtomic from "../hooks/withAtomic";
import { Popover, PopoverContent, PopoverTrigger } from "@radix-ui/themes";


export const imageBlockName = "IMAGE"
const IMAGE = ({
    editorState,
    onChange
}: RichEditorProps) => {
    const open = useOpenFile({
        accept: "image/*",
        callback(file) {
            const name = file.name;
            const suffix = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
            if (suffix === "gif") {

            } else {
                file2canvas(file).then((canvas) => {
                    insertBlock(onChange, editorState, imageBlockName, {
                        base64: canvas.toDataURL("jpg"),
                        type: "image",
                        width: canvas.width,
                        height: canvas.height
                    })
                })
            }
        },
    });
    return (
        <ToggleButton
            onMouseDown={open}
        >
            <ImageIcon />
        </ToggleButton>
    )
}
export const AtomicImage = withAtomic<{
    base64: string,
    url: string,
    type: string,
    width: number,
    height: number
}>(({
    data: {
        url,
        base64
    },
    blockProps: {
        readOnly
    }
}) => {

    return (
        <Popover.Root >
            <PopoverTrigger className="PopoverTrigger">
                <img src={!!url ? url : base64} />
            </PopoverTrigger>
            <PopoverContent className="PopoverContent">
                content
            </PopoverContent>
        </Popover.Root>
    )
})
export default IMAGE